<?php

if (!defined('SHOW_SYNTAX')) { die(); }

// Autolib definitions {{{
$autoloadfiles = array(
    'ZendLibraries' => array(
        /* 1.00 */ 'library/Zend/Controller/Router/Abstract.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Rewrite.php',
        /* 1.00 */ 'library/Zend/Controller/Dispatcher/Interface.php',
        /* 1.00 */ 'library/Zend/Controller/Dispatcher/Abstract.php',
        /* 1.00 */ 'library/Zend/Controller/Dispatcher/Standard.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Route/Static.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Route/Module.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Exception.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Route.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Interface.php',
        /* 1.00 */ 'library/Zend/Controller/Router/Route/Interface.php',
        /* 1.00 */ 'library/Zend/Db.php',
        /* 1.00 */ 'library/Zend/Db/Exception.php',
        /* 1.00 */ 'library/Zend/Db/Adapter/Pdo/Abstract.php',
        /* 1.00 */ 'library/Zend/Db/Expr.php',
        /* 1.00 */ 'library/Zend/Db/Profiler.php',
        /* 1.00 */ 'library/Zend/Db/Table/Row.php',
                   'library/Zend/Db/Table/Exception.php',
                   'library/Zend/Db/Table/Row/Exception.php',
        /* 1.00 */ 'library/Zend/Uri/Exception.php',
        /* 1.00 */ 'library/Zend/Uri/Http.php',
        /* 1.00 */ 'library/Zend/Uri/Mailto.php',
        /* 1.00 */ 'library/Zend/Uri.php',
        /* 1.00 */ 'library/Zend/Controller/Action/Helper/Abstract.php',
        /* 1.00 */ 'library/Zend/Controller/Action/Helper/ViewRenderer.php',
        /* 1.00 */ 'library/Zend/Controller/Action/Exception.php',
        /* 1.00 */ 'library/Zend/Controller/Action/HelperBroker.php',
        /* 1.00 */ 'library/Zend/Validate/Interface.php',
        /* 1.00 */ 'library/Zend/Validate/Abstract.php',
        /* 0.98 */ 'library/Zend/Validate/Hostname.php',
        /* 1.00 */ 'library/Zend/Validate/Ip.php',
        /* 1.00 */ 'library/Zend/Session.php',
        /* 1.00 */ 'library/Zend/Session/Abstract.php',
        /* 1.00 */ 'library/Zend/Session/Exception.php',
        /* 1.00 */ 'library/Zend/Session/Namespace.php',
        /* 1.00 */ 'library/Zend/Session/SaveHandler/Interface.php',
        /* 1.00 */ 'library/Zend/Exception.php',
        /* 1.00 */ 'library/Zend/Cache.php',
        /* 1.00 */ 'library/Zend/Loader.php',
        /* 1.00 */ 'library/Zend/View/Interface.php',
        /* 1.00 */ 'library/Zend/View/Abstract.php',
        /* 1.00 */ 'library/Zend/View.php',
        /* 1.00 */ 'library/Zend/Config.php',
        /* 1.00 */ 'library/Zend/Config/Exception.php',
        /* 1.00 */ 'library/Zend/Db/Adapter/Pdo/Mysql.php',
        /* 1.00 */ 'library/Zend/Db/Statement/Pdo.php',
        /* 1.00 */ 'library/Zend/Controller/Plugin/ErrorHandler.php',
        /* 1.00 */ 'library/Zend/Controller/Plugin/Abstract.php',
        /* 1.00 */ 'library/Zend/Db/Table/Abstract.php',
        /* 1.00 */ 'library/Zend/Controller/Exception.php',
        /* 1.00 */ 'library/Zend/Controller/Plugin/Broker.php',
        /* 1.00 */ 'library/Zend/Controller/Request/Abstract.php',
        /* 1.00 */ 'library/Zend/Db/Table/Rowset/Abstract.php',
        /* 1.00 */ 'library/Zend/Cache/Backend.php',
        /* 1.00 */ 'library/Zend/Cache/Core.php',
        /* 1.00 */ 'library/Zend/Controller/Action.php',
        /* 1.00 */ 'library/Zend/Config/Ini.php',
        /* 1.00 */ 'library/Zend/Controller/Request/Exception.php',
        /* 1.00 */ 'library/Zend/Cache/Backend/Interface.php',
        /* 1.00 */ 'library/Zend/Cache/Backend/Apc.php',
                   'library/Zend/Cache/Exception.php',
        /* 1.00 */ 'library/Zend/Controller/Request/Http.php',
        /* 1.00 */ 'library/Zend/Db/Statement/Interface.php',
        /* 1.00 */ 'library/Zend/Db/Select.php',
        /* 1.00 */ 'library/Zend/Db/Table/Row/Abstract.php',
        /* 1.00 */ 'library/Zend/Db/Adapter/Exception.php',
        /* 1.00 */ 'library/Zend/Db/Adapter/Abstract.php',
        /* 1.00 */ 'library/Zend/Db/Profiler/Query.php',
        /* 1.00 */ 'library/Zend/Controller/Response/Http.php',
        /* 1.00 */ 'library/Zend/Controller/Front.php',
        /* 1.00 */ 'library/Zend/Controller/Response/Abstract.php',
        /* 0.95 */ 'library/Zend/View/Helper/FormText.php',
        /* 0.95 */ 'library/Zend/View/Helper/FormSubmit.php',
        /* 0.95 */ 'library/Zend/View/Helper/FormElement.php',
        /* 0.95 */ 'library/Zend/View/Helper/FormHidden.php',
        /* 0.95 */ 'library/Zend/View/Helper/FormSelect.php',
        /* 0.95 */ 'library/Zend/View/Helper/FormTextarea.php',
        /* 1.00 */ 'library/Zend/Cache/Frontend/File.php',
    ),

    'GM Libraries' => array(
        /** GM LIBRARY MODULES WHICH LOADED EACH REQUEST **/
        /* 1.00 */ 'library/GM/View.php',
        /* 1.00 */ 'library/GM/Controller/Front.php',
        /* 1.00 */ 'library/GM/Controller/Action.php',
        /* 1.00 */ 'library/GM/Interface/Module.php',
        /* 1.00 */ 'library/GM/Db.php',
        /* 1.00 */ 'library/GM/Db/Table/Rowset/Abstract.php',
        /* 1.00 */ 'library/GM/Db/Table/Row/Abstract.php',
        /* 1.00 */ 'library/GM/Db/Table/Abstract.php',
        /* 1.00 */ 'library/GM/Db/Select.php',
        /* 1.00 */ 'library/GM/Db/Adapter/Pdo/Mysql.php',
        /* 0.79 */ 'library/GM/Db/Table/Row/User.php',
        /* 1.00 */ 'library/GM/Module.php',
        /* 1.00 */ 'library/GM/Skeletion/Base.php',
    ),

    'GM Models' => array(
        /** GM MODELS **/
        /* 1.00 */ 'library/GM/Model/ArticleTag.php',
        /* 1.00 */ 'library/GM/Model/Article.php',
        /* 1.00 */ 'library/GM/Model/ArticleComment.php',
        /* 1.00 */ 'library/GM/Model/ArticleRating.php',
        /* 1.00 */ 'library/GM/Model/User.php',
        #/* 0.00 */ 'library/GM/Model/Meta.php',
        #/* 0.00 */ 'library/GM/Model/Relation/ArticleTag.php'
    ),

    'GM Modules' => array(
        /** GM MODULES **/
        /* 1.00 */ 'application/modules/GM_Module_Debug/GM_Module_Debug.php',
        /* 1.00 */ 'application/modules/GM_Module_Db/GM_Module_Db.php',
        /* 1.00 */ 'application/modules/GM_Module_Article/GM_Module_Article.php',
        /* 1.00 */ 'application/modules/GM_Module_User/GM_Module_User_Exception.php',
        /* 1.00 */ 'application/modules/GM_Module_User/GM_Module_User.php',
        /* 1.00 */ 'application/modules/GM_Module_RamCache/GM_Module_RamCache.php',
        /* 1.00 */ 'application/modules/GM_Module_Menu/GM_Module_Menu.php',
        /* 1.00 */ 'application/modules/GM_Module_HtmlMeta/GM_Module_HtmlMeta.php',
        /* 1.00 */ 'application/modules/GM_Module_Conf/GM_Module_Conf.php',
        /* 1.00 */ 'application/modules/GM_Module_Menu/GM_Module_Menu_Root.php',
        /* 1.00 */ 'application/modules/GM_Module_Menu/GM_Module_Menu_Item.php'
    ),

    'GM Skeletions' => array(
        /** GM SKELETIONS **/
        /* 1.00 */ 'application/views/skeletions/GM_Skeletion_Default.php'
    ),
    'Default' => array(
        /* 1.00 */ 'application/bootstrap.php'
    ),
    'Controllers' => array(
                   #'application/controllers/ArticleController.php'
    )
); //}}}


$apc_stat_files = array();
$stat_files = array();

/* MAKE LIST FROM APC_INFO {{{ */
$ai = apc_cache_info('opcode');
$ac = $ai['cache_list'];
$max_h = 0;

array_walk($ac, create_function('&$item, $key', 'global $max_h; if ($max_h < $item["num_hits"]) $max_h = $item["num_hits"];'));

$apc_stat_files = array();

foreach ($ac as $entry) {
    $p = sprintf('%0.2f', $entry['num_hits'] / $max_h);
    $h = $entry['num_hits'];

    if (substr($entry['filename'], -4) == '.php' &&
        substr($entry['filename'], -12) != 'ZendFull.php') {
        $apc_stat_files[] = array($entry['filename'], $p, $h);
    }
} // }}}

function search_in_autoload_files($filename)
{
    global $autoloadfiles;
    foreach ($autoloadfiles as $a => $cat) {
        if (!is_array($cat)) {
            if ($cat == $filename) return true;
        } else if (array_search($filename, $cat) !== false) {
            return true;
        }
    }

    return false;
}

$basedir = realpath('../..');
foreach ($apc_stat_files as $key => $apc_file) {
    $filename = $apc_file[0];
    $hits = $apc_file[2];

    $filename = str_replace($basedir . '/', '', $filename);

    if (preg_match("/^library\/Zend/", $filename)) {
        $category = 'Zend Libraries';
    } else if (preg_match("/^library\/GM\/Model/", $filename)) {
        $category = 'GM Models';
    } else if (preg_match("/^library\/GM/", $filename)) {
        $category = 'GM Libraries';
    } else if (preg_match("/^application\/modules/", $filename)) {
        $category = 'GM Modules';
    } else if (preg_match("/^application\/views\/skeletions/", $filename)) {
        $category = 'GM Skeletions';
    } else {
        $category = 'Default';
    }

    $stat_files[$category][] = array('filename' => $filename, 'hits' => $hits);
}

function cmp($a, $b)
{
    if ($a['hits'] == $b['hits']) return 0;
    return $a['hits'] < $b['hits'];
}

foreach ($stat_files as &$st) {
    usort($st, 'cmp');
}

foreach ($stat_files as $category => $file) {
    echo "<h1>$category</h1>";
    ?>
    <table cellspacing="0" cellpadding="5" border="1">
    <?php
    foreach ($file as $f) {
        ?>
        <tr style="background: <?php if (search_in_autoload_files($f['filename'])) { echo "green"; } else { echo "red"; } ?>">
            <td>
                <?=$f['filename'];?>
            </td>
            <td>
                <?=$f['hits'];?>
            </td>
            <td>
                <?php printf("%0.0f%%", $f['hits'] / $max_h * 100); ?>
            </td>
        </tr>
        <?php
    }
    echo '</table>';
}

function generate_file($fn, $arr)
{
    $fp = fopen($fn, 'w');
    foreach ($arr as $category => $files) {
        foreach ($files as $filename) {
            echo 'Writing ' . $filename . '<br/>';
            $content = file_get_contents(realpath('../..') . '/' . $filename);
            if (substr($filename, -13) == 'bootstrap.php') {
                $remove_require_once = false;
            } else {
                $remove_require_once = true;
            }
            $content_c = extract_good_source($content, $remove_require_once);
            fwrite($fp, $content_c);
        }
    }
}

function extract_good_source($src, $remove_require = false)
{
    $result = '';
    $tokens = token_get_all($src);
    $skip_next = 0;
    $skip_all_until_dots = false;
    $php_started = false;
    foreach ($tokens as $cur => $token) {
        if (is_string($token)) {
            if ($skip_all_until_dots && $token == ';') {
                $skip_all_until_dots = false;
            } else if (!$skip_all_until_dots){
                $result .= $token;
            }
        } else if (!$skip_all_until_dots) {
            if ($token[0] == T_OPEN_TAG) {
                $php_started = true;
            } else if ($token[0] == T_CLOSE_TAG) {
                $php_started = false;
            }
            switch ($token[0]) {
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;

                case T_REQUIRE_ONCE:
                    if ($remove_require) {
                        $skip_all_until_dots = true;
                        break;
                    }
                    // fall throught default case

                default:
                    $result .= $token[1];
            }
        }
    }
    if ($php_started) {
        $result .= ' ?>';
    }

    $tokens = token_get_all($result);
    $result = '';
    foreach ($tokens as $token) {
        if (is_string($token)) {
            $result .= $token;
        } else {
            switch ($token[0]) {
                case T_WHITESPACE:
                    $result .= preg_replace("/(\n\ *\n)+/", "\n", $token[1]);
                    break;

                default:
                    $result .= $token[1];
            }
        }
    }

    $result = str_replace("\r\n", "\n", $result);
    $result = str_replace("\r", "", $result);

    return $result;
}

if (@$_GET['SAVEFILE'] == 'Y') {
    generate_file(realpath('../../library/__auto_require.php'), $autoloadfiles);
}